/**
 * @Description:
 * @author 紫霞
 * @since 2019/1/17
 */
// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
// 引入antd的组件
import {
    Form,
    Row,
    Col,
    Input,
    Cascader,
    Tag,
    Icon,
    DatePicker,
    Select,
    Button,
    Upload,
    Modal,
    Divider,
    Tooltip,
    message,
    Radio, Checkbox
} from 'antd'
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config'
import {isEmpty, isArray, cloneDeep, chunk, set, get} from 'lodash'

// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
import { reg } from 'utils/util'
// 当前组件样式
import styles from './commodityEditStyle.less'
import ListPage from 'widget/PageTmpl/ListPage'

import { CollapsiblePanels } from 'widget/CollapsiblePanels/index'
// import Editor from '../../../../widget/Editor/Editor.js'
// import Editor from '../../../../AppBus'
import Uploader from "../../../../widget/Upload";
import classnames from 'classnames/bind'
import Ueditor from "../../../../widget/Editor/Ueditor.js";

let cx = classnames.bind(styles);
const { Option } = Select;
const FormItem = Form.Item
const { TextArea } = Input
const InputGroup = Input.Group;
const RadioGroup = Radio.Group;
const formItemLayout = {
    labelCol: { span: 2 },
    wrapperCol: { span: 8 },
}
const formItemLayout1 = {
    labelCol: { span: 2 },
    wrapperCol: { span: 20 },
}
const formItemLayout2 = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
}
const imageLayout = {
    labelCol: { span: 2 },
    wrapperCol: { span: 22 },
}
/**
 * description 路由视图及事件处理
 * dispatch 分发到models中的effects对应事件名
 * model 用于获取models中state定义的数据
 * form 表单对象
 */



const routeView = function ({ dispatch, model, form }) {
    // 表单的子函数
    const { resetFields, getFieldDecorator, validateFields, setFieldsValue } = form
    // 取出model对象，命名空间
    const { modelObj, namespace } = model
    let { pageType, id, modalObj, medias, formData, detailInfo, fileList, houseList, allAddress, houseTypeList ,accountList,loading,selectOption,teamsOptions,areaList1,biz} = modelObj
    // modelObj.xxx获取model中状态机的值


    console.log('routeView', modelObj)

    //修改状态
    const changeState = (payload) => {
        console.log(payload)
        dispatch({
            type: `${namespace}/updateStore`,
            payload: { ...payload }
        })
    }
   let pageProps = {   //楼盘
        // ---------- 界面部分 ----------
        ui: {
          // 页面接口地址
          api_url: 'admin/estate/adminList',
          // 接口方式
          method: 'POST',
          headers: {
            'Content-type': 'application/json'
          },
          app: '',
          // 接口参数
          params:biz.queryForm,
            // 模拟数据 - 用于开发需要，若填充了上面的api_url之后，请将此项设置为null
            // "mockData": mockData,
            mockData: null,

            selectedRowKeys:biz.selectedRowKeys,
          // 查询栏
          search_bar: {
            fields: [
              {
                en_name: 'province',
                zh_name: '城市',
                elem_type: 'Cascader',
                elem_valid_type: 'string',
                changeOnSelect: true,
                cmpt_items: allAddress,
                split_keys: ['province', 'city'],
              },
              {
                en_name: 'name',
                zh_name: '项目名称',
                elem_type: 'Input',
                elem_valid_type: 'string',
              },
              // {
              //   en_name: 'shelfStatus',
              //   zh_name: '状态',
              //   elem_type: 'Select',
              //   cmpt_items: [
              //     {value: null, label: '全部'},
              //     {value: '0', label: '未上架'},
              //     {value: '1', label: '已上架'},
              //     {value: '2', label: '已下架'},
              //   ],
              //   elem_valid_type: 'string',
              // },
            ],
            searchHandler: (e) => { // 自定义搜索按钮回调函数，点击搜索时触发
              console.log('search click', e)
            },
            resetHandler: () => { // 自定义重置按钮回调函数，点击重置时触发
              console.log('reset click')
            },
            searchCallback: params => { // 自定义搜索完成后的后调函数, 搜索完成后触发, 并将本次搜索的参数传入
              console.log('search finish', params)
            },
            pasteTargetList: [  // 列表组件中将输入框的en_name作为默认id(也可以通过id另外设置)
              'carName',  // 将需要粘贴事件拦截的输入框id以数组的形式传入, 该参数对应PasteFromClipboard组件的targetList参数
            ]
          },
          // 数据表格
          'table':
            {
              rowSelectionInfo: {
                type: 'radio',
              },
              key: 'productId',
              status_params: 'status=0',
              status_text: '全部',
              // 表头字段列表
              scroll: {x: 800},
              fields: [
                {
                  en_name: 'estateCode',
                  zh_name: '项目编号',
                  // width: 150,
                },
                {
                  en_name: 'name',
                  zh_name: '项目名称',
                  // width: 100,
                },
                {
                  en_name: 'cityName',
                  zh_name: '所属城市',
                  width:150,
                  // width: 100,
                  render: (a, item, index, d, e, f) => {
                    let arr = ['北京市', '重庆', '上海', '天津']
                    if (arr.indexOf(item.provinceName) > -1) {
                      return item.cityName
                    } else {
                      return `${item.provinceName||''}${item.provinceName&&item.cityName&&' - '||''}${item.cityName||''}`
                    }
                    
                  }
                },
                {
                  en_name: 'shelfStatus',
                  zh_name: '状态',
                  width: 80,
                  render: (a, item, index, d, e, f) => {
                    let shelfStatus = ['未上架', '已上架', '已下架']
                    return (
                      <span>{shelfStatus[item.shelfStatus]}</span>
                    )
                  }
                },
                {
                  en_name: 'createPerson',
                  zh_name: '创建人',
                  // width: 100,
                },
                {
                  en_name: 'createTime',
                  zh_name: '创建时间',
                  width: 180
                },
              ],
              // 表格操作
              actions: [],
            },
          action_bar: [
            {
              // label:'',
              // type:'',
              rowSelection: [],
              render: () => {
                return <Input hidden/>
              },
              onClick: (e, row) => {
              }
            },
          ]
        },
      }

    // 新
    // 弹窗
    function inputChange (value, key, index) {
        // if (key == 'productType') {
        //     formData.productLabel = productTypeLabelMap[value] || null
        //     formData['productType']=value
        // }
       if (key == 'areaId') {
            formData.province = value[0]
            formData.city = value[1]
            formData.projectId = ''
            formData.projectName = ''
            setFieldsValue({'parentProductId':''})
            dispatch({type: `${namespace}/houseListGet`, payload: {province: value[0], city: value[1]}})
        }
        // else if (key.indexOf('houseTypeName') > -1) {
        //     key = key.split('_')
        //     formData.houseTypeName[key[1]] = value
        // }
        else if (key == 'parentProductId') {
            formData[key] = value
            houseList.map((item,index)=>{//项目名称
                if(item.value==value){
                    formData['parentProductName']=item.label
                }
            })
            updateModal('project')
            setFieldsValue({'parentProductId':value})
            dispatch({type: `${namespace}/queryAccount`, payload: {id: value,}})
        } else {
            formData[key] = value
        }
        changeState({formData})

    }

    //校验
    function validator(rule, value, callback, type = '') {
        console.warn('validator :rule, value, callback, type', rule, value, type);
        if (value && (isNaN(value) || !/^\d+(\.\d{1,2})?$/.test(value))) {
            callback('请输入数字（最多两位）')
        }
        else if (value > 999999999.99 || value < 0) {
            callback('数字范围在0-99999999.99之间')
        }
        else {
            callback()
        }
    }

    // updateProduct createProduct
    function save() {
        let methodName={ edit: 'update', add: 'create', detail: '' }[pageType]
        if(modelObj.isClone){//clone方式新建
            methodName='create'
        }
        validateFields((err) => {
            if (err) {
                return false
            } else {
                dispatch({
                    type: `${namespace}/${methodName}`,
                    payload: {resetFields}
                })
            }
        })
    }

    // 筛选项目名称下拉列表
    function filter(inputValue, path) {
        return (path.some(option => (option.label).toLowerCase().indexOf(inputValue.toLowerCase()) > -1))
    }


    function updateImageModel(value) {
        medias.push({fileUrl: value,busiType:'seckill',fileType:'1'});
        // 分发到model
        dispatch({
            type: `${namespace}/updateStore`,
            payload: { medias }
        })
    };

    function removeImgUrl(index) {
        medias.splice(index, 1)
        dispatch({
            type: `${namespace}/updateStore`,
            payload: { medias }
        })
    }
    function updateModal (modalName) {
        modalObj[modalName].visible=!modalObj[modalName].visible
        changeState({modalObj})
        if(modalName=='project'){
            dispatch({
              type:`${namespace}/houseListGet`,
              payload:{}
            })
          }
    }
    //添加规则
    // function add (idx) {
    //     let arr = formData.teams
    //     if(arr.length > 2) {
    //         message.info('不能再添加了')
    //         return
    //     }
    //     formData.teams.push({
    //         optionValue: 1,
    //         optionDes: ''
    //     })
    //
    //     set(formData,'teams',arr)
    //     changeState({formData})
    // }
    // -----------标签--结束--------
    function confirm(){
        modalObj.project.visible=false
        dispatch({
            type:`${namespace}/updateStore`,
            payload:{
                formData:{
                    ...formData,
                    parentProductId:biz.selectedRows[0].productId ,
                    parentProductName:biz.selectedRows[0].name,
                    modalObj,
                }
            }
        })
    }
    let fileUrl = medias.map(item => item.fileUrl)
    if (!!modelObj.biz) {
        pageProps.biz = modelObj.biz
        pageProps.biz.syncBackCbf = (biz) => {
            biz.selectedRowKeys=pageProps.biz.selectedRowKeys
          dispatch({
            type: `${namespace}/updateStore`,
            payload: { biz }
          })
        }
      }
    return (
        <div className={cx('public_listMain')}>
            <div className="functionButton">
                {
                    pageType=='detail'?null:<Button type='primary' loading={modelObj.btnLoading} onClick={() => { save() }}>保存</Button>
                }
                
            </div>

            <CollapsiblePanels title="商品信息" hideUpDownBtn={true}>
                <div className={''}>
                    <Row className="col" >
                        <Col className="col" span={24}>
                            <FormItem {...formItemLayout} label={'所属项目'}>
                                {getFieldDecorator('parentProductId', {
                                    initialValue: formData.parentProductId,
                                    rules: [
                                        { required: true,  message: '请选择所属项目' },
                                    ],
                                })(
                                    <div>
                                        <text>{formData.parentProductName||''}</text>
                                        {pageType=='detail'?null:
                                            <a href="javascript:void(0)" onClick={()=>{updateModal('project')}} className={'mgl1'}>{'选择'}</a>
                                        }
                                        
                                    </div>
                                )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row className="col" >
                        <Col span={24}>
                            <FormItem {...formItemLayout}
                                      label="商品类型">
                                {getFieldDecorator(`catalogId`, {
                                    initialValue:  formData.catalogId || '',
                                    rules: [
                                        { required: true, whitespace: true, message: '请选择商品类型' },
                                    ],
                                })((<Select placeholder="请选择" disabled={pageType == 'detail'}  onChange={(val) => inputChange(val, 'catalogId')} >
                                    <Select.Option value="9004">日用快消</Select.Option>
                                    <Select.Option value="9005">家电数码</Select.Option>
                                    <Select.Option value="9006">首饰箱包</Select.Option>
                                    <Select.Option value="9009">其他</Select.Option>
                                </Select>))}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row className="col" >
                        <Col span={24}>
                            <FormItem {...formItemLayout}
                                      label='商品名称'>
                                {getFieldDecorator('name', {
                                    initialValue: formData.name,
                                    rules: [
                                        { required: true,  message: '请输入商品名称'},
                                    ],
                                })(<Input
                                    disabled={pageType == 'detail'}
                                    placeholder={'请输入商品名称'}
                                    onChange={(e) => { inputChange(e.target.value, 'name') }}
                                />)}
                            </FormItem>
                        </Col>

                    </Row>
                    <Row className="col" >
                        <Col span={24}>
                            <FormItem {...formItemLayout}
                                      label="规则">
                                <InputGroup compact>
                                    <Select
                                        onChange={value=>{

                                            selectOption.value = value
                                            changeState({selectOption})

                                        }}
                                        disabled={pageType == 'detail'}
                                        value={selectOption.value} style={{width:'30%'}}>
                                        {teamsOptions.map((option, idx)=>(
                                            <Select.Option
                                                key={`option${idx}`} value={option.value}>{option.label} </Select.Option>
                                        ))}

                                    </Select>
                                    <Input
                                        disabled={pageType == 'detail'}
                                        style={{width:'70%'}}
                                        value={selectOption.des || formData.volume || formData.weight || formData.power || formData.size ||  formData.color ||  formData.producingArea || formData.other}
                                        onChange={(e)=>{

                                            selectOption.des = e.target.value
                                            changeState({selectOption})

                                        }}
                                    />
                                </InputGroup>
                            </FormItem>
                        </Col>
                    </Row>
                    <Row className="col" >
                        <Col span={6}>
                            <FormItem {...formItemLayout2}
                                      label='参考价格'>
                                {getFieldDecorator('price', {
                                    initialValue: formData.price,
                                    rules: [
                                        { required: false,  message: '请输入参考价格'},
                                    ],
                                })(<Input width='70%'
                                    disabled={pageType == 'detail'}
                                    placeholder={'请输入参考价格'}
                                    onChange={(e) => { inputChange(e.target.value, 'price') }}
                                />)}
                            </FormItem>
                        </Col>
                        <Col><span style={{height:'40px',lineHeight:'40px',marginLeft:'2px'}}>元</span></Col>
                    </Row>
                    
                </div>
            </CollapsiblePanels>
            <CollapsiblePanels title="商品图" hideUpDownBtn={true}>
                <Row>
                    <FormItem{...imageLayout} label="商品图">
                        <Uploader uploadedUrls={fileUrl }
                                  removeFileCbf={(index) => { removeImgUrl(index) }}
                                  uploadSuccessCbf={(imgUrl) => { updateImageModel(imgUrl) }}
                                  showType='3'
                                  fileType='image'
                                  fileMaxSize='0.2'
                                  minCropBoxWidth={1500}
                                  minCropBoxHeight={1280}
                                  maxFiles='10' />

                    </FormItem>

                    <Col span={12}>
            <span style={{ color: '#999', marginLeft: '4%' }}>
            图片分辨率需为1500px*1280px，且文件大小在200kb以下，支持jpg，png格式。
              </span>
                    </Col>
                </Row>
            </CollapsiblePanels>
            <CollapsiblePanels title="商品介绍" hideUpDownBtn={true}
                               style={{maxHeight:'300px',overflow:'auto'}}
            >
                <Row>
                    <Ueditor  id="infoDetail1"
                              style={{ width: '100%', height: '400px'}}
                              editable={pageType == 'detail'?false:true}
                              html={formData.description || ''}
                              startDate=''
                              endDate=''
                              // height={300}
                                    inputChange={(e) => { inputChange(e, 'description') }}
                          
                    />
                </Row>
            </CollapsiblePanels>
            {/*选择项目弹窗*/}
            <Modal
                title={'所属项目'}
                width='1000px'
                // className="pubBiz_CommonModel"
                visible={modalObj['project'].visible}
                onCancel={() => { updateModal('project') }}
                onOk={() => { confirm() }}
            >
                <div className={''}>
                    {/* <Row>
                        <FormItem {...formItemLayout1} label="区域" >
                            {getFieldDecorator('areaId', {
                                initialValue: [formData.province||'', formData.city||''],
                                // rules: [
                                //   { required: true,  message: '请选择所属项目' },
                                // ],
                            })(
                                <Cascader style={{width: '50%'}} disabled={pageType == 'detail'} options={allAddress}
                                    // value={[formData.province||'', formData.city||'']}
                                          onChange={(value, selectedOptions) => inputChange(value, 'areaId')}
                                          placeholder="请选择项目"/>
                            )}
                        </FormItem>
                    </Row> */}

                    <Row>
                        {/* <FormItem {...imageLayout} label="项目" >
                            <RadioGroup name={'project'}  options={houseList}  value={formData.parentProductId} onChange={(e) =>{ inputChange(e.target.value, 'parentProductId')}}  />
                        </FormItem> */}
                        <ListPage pageProps={pageProps}/>
                    </Row>
                </div>
            </Modal>
        </div>
    )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(routeView))

